package com.xuanwei.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import com.xuanwei.core.response.ResultVO;
import com.xuanwei.core.service.IXwUserService;
import com.xuanwei.core.util.HttpClient;
import com.xuanwei.dao.entity.XwUser;
import com.xuanwei.web.cache.RedisCache;
import com.xuanwei.web.config.WxAppConfig;
import com.xuanwei.xwcommon.consts.CacheName;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.web.bind.annotation.*;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author jiangyong
 * @Description TODO
 * @Date 2019/7/8 14:38
 **/
@RestController
@RequestMapping("wx/auth")
public class LoginController extends BasicController {

    private WxAppConfig wxAppConfig;

    private RedisCache redisCache;

    private IXwUserService userService;

    public LoginController(WxAppConfig wxAppConfig, RedisCache redisCache, IXwUserService userService) {
        this.wxAppConfig = wxAppConfig;
        this.redisCache = redisCache;
        this.userService = userService;
    }

    @RequestMapping(value = "getOpenId", method = RequestMethod.GET)
    public ResultVO getOpenId(String code) {
        if (StringUtils.isBlank(code)) {
            return ResultVO.failResult("获取失败");
        }
        Map<String, String> param = new HashMap<>(4);
        param.put("appid", wxAppConfig.getAppid());
        param.put("secret", wxAppConfig.getSecret());
        param.put("js_code", code);
        param.put("grant_type", wxAppConfig.getGrantType());
        try {
            HttpClient.HttpClientResult httpClientResult = HttpClient.doGet(wxAppConfig.getLoginUrl(), param);
            String json = httpClientResult.getContent();
            JSONObject jsonObject = JSON.parseObject(json);
            String session_key = jsonObject.getString("session_key");
            //保存session_key
            redisCache.setCache(CacheName.WX_SESSION_KEY, session_key);
            String openid = jsonObject.getString("openid");
            return ResultVO.successResult("登录成功", openid);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVO.failResult("获取失败");
        }
    }

    @RequestMapping(value = "saveUser", method = RequestMethod.POST)
    public ResultVO saveUser(@RequestBody XwUser user) {
        if (user == null) {
            return ResultVO.failResult("参数为空");
        }
        if (StringUtils.isBlank(user.getMiniAppOpenid())) {
            return ResultVO.failResult("openID不能为空");
        }
        String ip = getIpAddress();
        String ipAddress = getIpAddress(ip);
        String token = userService.saveUser(user, ip, ipAddress);
        return ResultVO.successResult("",token);
    }

    /**
     * 将微信加密数据解密
     *
     * @param encryptedData 数据包
     * @param sessionkey    key
     * @param iv            向量
     * @return json 数据
     */
    private JSONObject getUserInfo(String encryptedData, String sessionkey, String iv) {
        // 被加密的数据
        byte[] dataByte = Base64.decode(encryptedData);
        // 加密秘钥
        byte[] keyByte = Base64.decode(sessionkey);
        // 偏移量
        byte[] ivByte = Base64.decode(iv);
        try {
            // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                return JSONObject.parseObject(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
